<template>
  <div class="login_container">
    <div class="login_box card">
      <div><p style="font-size: 50px; font-weight: bolder; color: cornflowerblue">欢迎登录</p></div>
      <div class="login_form">
        <div class="role-buttons">
          <el-button class="role-button" size="large" :class="{ active: data.role === 1 }" @click="data.role = 1">
            商家版
          </el-button>
          <span class="role-separator">|</span>
          <el-button class="role-button" size="large" :class="{ active: data.role === 2 }" @click="data.role = 2">
            用户版
          </el-button>
        </div>
        <el-form :rules="data.rules" style="width: 100%" ref="formRef" :model="data.form">
          <el-form-item prop="username">
            <el-input class="el-input" v-model="data.form.username" placeholder="请输入用户名"
                      prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input class="el-input" v-model="data.form.password" placeholder="请输入密码"
                      prefix-icon="Key"></el-input>
          </el-form-item>
        </el-form>
        <div style="text-align: center; position: relative;">
          <el-button type="success" style="width: 70%; height: 40px;" @click="login">登录</el-button>
          <div style="padding: 10px">还没有账号？请<a href='http://localhost:5173/register'>注册</a></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import '@/assets/css/Login.css'
import request from "@/utils/request.js";
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";

const data = reactive({
  form: {},
  role: 1,
  rules: {
    username: [{required: true, message: "请输入账号", trigger: "blur"}],
    password: [{required: true, message: "请输入密码", trigger: "blur"}],
  }
});
const formRef = ref();
const login = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (data.role === 1) {
        request.post("/login/business", data.form).then(res => {
          if (res.code === 200) {
            ElMessage.success('登录成功！！！')
            localStorage.setItem("information", JSON.stringify(res.data))
            console.log("json" + JSON.parse(localStorage.getItem("information")));
            setTimeout(() => {
              location.href = "/business/item";
            }, 500)
          } else {
            ElMessage.error("请检查账号或密码")
          }
        })
      } else {
        request.post("/login/user", data.form).then(res => {
          if (res.code === 200) {
            ElMessage.success('登录成功！！！')
            localStorage.setItem("user_information", JSON.stringify(res.data))
            console.log("json" + JSON.parse(localStorage.getItem("user_information")));
            setTimeout(() => {
              location.href = "/home";
            }, 500)
          } else {
            ElMessage.error("请检查账号或密码")
          }
        })

      }
    }
  })
}
</script>

<style scoped>

</style>